package com.iemes.controller.work_plan;

import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;
import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.iemes.annotation.SystemLog;
import com.iemes.entity.FlowStepFormMap;
import com.iemes.entity.NumberRuleFormMap;
import com.iemes.entity.ShopOrderSfcFormMap;
import com.iemes.entity.ShoporderFormMap;
import com.iemes.exception.BusinessException;
import com.iemes.mapper.base.BaseMapper;
import com.iemes.service.CommonService;
import com.iemes.service.impl.workcenter_model.NumberRuleServiceImpl;
import com.iemes.service.work_plan.ShoporderIssuingService;
import com.iemes.service.workcenter_model.NumberRuleService;
import com.iemes.util.Common;
import com.iemes.util.DateUtils;
import com.iemes.util.ListUtils;
import com.iemes.util.ResponseHelp;
import com.iemes.util.ShiroSecurityHelper;


/**
 * 
 */
@Controller
@RequestMapping("/work_plan/shoporder_issuing/")
public class ShoporderIssuingController extends ShoporderMaintenanceController {
	
	@Inject
	private BaseMapper baseMapper;
		
	@Inject
	private CommonService commonService;
	
	@Inject
	private NumberRuleService numberRuleService;
	
	@Inject
	private ShoporderIssuingService shoporderIssuingService;
	
	private Logger log = Logger.getLogger(this.getClass());
	private String shoporderIssuingUrl = Common.BACKGROUND_PATH + "/work_plan/shoporder_issuing/shoporder_issuing";

	//页面跳转
	@RequestMapping("shoporder_issuing")
	public String Get_shoporder_issuing_Url(Model model) throws Exception {
		model.addAttribute("res", findByRes());
		return shoporderIssuingUrl;
	}
	
	/**
	 * 下达工单
	 * @return
	 */
	@ResponseBody
	@RequestMapping("issuingShoporder")
	@SystemLog(module="工单下达",methods="工单下达-下达工单")		//凡需要处理业务逻辑的.都需要记录操作日志
	public String issuingShoporder() {
		ShoporderFormMap shoporderFormMap = getFormMap(ShoporderFormMap.class);
		shoporderFormMap.put("create_time", DateUtils.getStringDateTime());
		shoporderFormMap.put("create_user", ShiroSecurityHelper.getCurrentUsername());
		shoporderFormMap.put("site_id", ShiroSecurityHelper.getSiteId());	
	
		try {
			issuingShoporder(shoporderFormMap);
		} catch (BusinessException e) {
			log.error(e.getMessage());
			return ResponseHelp.responseErrorText(e.getMessage());
		}
		return ResponseHelp.responseText();
	}
	
	public void issuingShoporder(ShoporderFormMap shoporderFormMap) throws BusinessException {
		try {
			String id = shoporderFormMap.getStr("id");
			String siteId = ShiroSecurityHelper.getSiteId();
			/*
			 * 1、如果工单状态为已完成（3）、关闭（4）、挂起（5）、已删除（6），则不允许下达。
			 * 2、判断当次下达数量+已下达数量是否超过工单需要下达的总数量，超过则抛异常。 3、如果工单状态为下达（1）、生产中（2），则不需要修改状态。
			 * 4、如果工单状态为创建（0），修改工单状态为下达（1）。
			 * 5、判断工单SFC编号是否是自动生成，如果不是，则不作任何处理；如果是，向mds_shoporder_sfc表插入sfc信息、
			 * 向mds_sfc_step表插入对应工艺路线的首操作，且状态为创建的记录。
			 * 6、向mds_shoporder_issuing_history添加工单下达的历史记录。
			 */
			if (StringUtils.isEmpty(id)) {
				throw new BusinessException("工单ID为空，不允许下达！请检索工单！");
			} else {
				ShoporderFormMap shoporderFormMap2 = new ShoporderFormMap();
				shoporderFormMap2.put("id", id);
				List<ShoporderFormMap> listShoporderFormMap = baseMapper.findByNames(shoporderFormMap2);
				if (ListUtils.isNotNull(listShoporderFormMap)) {
					// 1、如果工单状态为已完成（3）、关闭（4）、挂起（5）、已删除（6），则不允许下达。
					shoporderFormMap2 = listShoporderFormMap.get(0);
					int shoporderStatus = shoporderFormMap2.getInt("status");
					int[] cannotIssuingStatusArray = new int[] { 3, 4, 5, 6 };
					for (int status : cannotIssuingStatusArray) {
						if (shoporderStatus == status) {
							throw new BusinessException(
									"工单处于" + commonService.getShoporderStatusStr(status) + "状态，不允许下达！");
						}
					}
					// 2、判断当次下达数量+已下达数量是否超过工单需要下达的总数量，超过则抛异常。
					Object obshoporderIssuingNumberNow = shoporderFormMap.get("issuing_number");
					int shoporderIssuingNumberNow = Integer.valueOf(obshoporderIssuingNumberNow.toString());// 当次需要下达数量
					int shoporderIssuedNumber = shoporderFormMap2.getInt("shoporder_issued_number");// 工单已下达数量
					int shoporderNumber = shoporderFormMap2.getInt("shoporder_number");// 工单总数量
					int canIssuingNumber = shoporderNumber - shoporderIssuedNumber;// 可下达数量
					if (shoporderIssuingNumberNow > canIssuingNumber) {
						throw new BusinessException(
								"工单下达数量" + shoporderIssuingNumberNow + "超过了可下达数量" + canIssuingNumber + "，不允许下达！");
					}
					shoporderFormMap2.set("shoporder_issued_number", shoporderIssuedNumber + shoporderIssuingNumberNow);
					// 3、如果工单状态为下达（1）、生产中（2），则不需要修改状态。
					// 无需处理

					// 4、如果工单状态为创建（0），修改工单状态为下达（1）。
					if (shoporderStatus == 0) {
						shoporderFormMap2.set("status", 1);
					}

					// 获取首个操作
					String processWorkflowId = shoporderFormMap2.getStr("process_workflow_id");
					FlowStepFormMap flowStepFormMap = new FlowStepFormMap();
					flowStepFormMap.put("process_workflow_id", processWorkflowId);
					flowStepFormMap.put("status", 1);
					List<FlowStepFormMap> listFlowStepFormMap = baseMapper.findByNames(flowStepFormMap);
					if (!ListUtils.isNotNull(listFlowStepFormMap)) {
						throw new BusinessException("无法获取工艺路线，请联系系统管理员！");
					}
					flowStepFormMap = listFlowStepFormMap.get(0);

					// 获取自动生成的sfc编号
					List<String> listSfcNo = new ArrayList<String>();
					int isSfcAutoGenerate = shoporderFormMap2.getInt("is_sfc_auto_generate");
					NumberRuleFormMap numberRuleFormMap = new NumberRuleFormMap();
					if (isSfcAutoGenerate == 1) {
						String numberRuleId = shoporderFormMap.getStr("number_rule_id");
						numberRuleFormMap.put("id", numberRuleId);
						listSfcNo = numberRuleService.generateNumberByNumberRule(numberRuleFormMap,
								shoporderIssuingNumberNow,false);
						numberRuleFormMap = NumberRuleServiceImpl.GetNumberRuleFormMapAfterHandle();
					}
					
					// 获取处于已存在的处于创建状态的sfc编号
					ShopOrderSfcFormMap shopOrderSfcFormMap = new ShopOrderSfcFormMap();
					shopOrderSfcFormMap.put("site_id", siteId);
					shopOrderSfcFormMap.put("sfc_status", 0);
					List<ShopOrderSfcFormMap> listShopOrderSfcFormMap = baseMapper.findByNames(shopOrderSfcFormMap);

					shoporderIssuingService.issuingShoporder(shoporderFormMap, 
							shoporderFormMap2, numberRuleFormMap, flowStepFormMap,
							listSfcNo, listShopOrderSfcFormMap);

				} else {
					throw new BusinessException("工单ID不存在，不允许下达！请联系系统管理员！");
				}
			}
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			throw new BusinessException(e.getMessage());
		}
	}

	/**
	 * 检索工单信息
	 * @param model
	 * @param request
	 * @return
	 */
	@RequestMapping("queryShoporder")
	public String queryShoporder(Model model, HttpServletRequest request) {
		String siteId = ShiroSecurityHelper.getSiteId();
		String shoporderNo = request.getParameter("shoporder_no");
		// 1.查询工单的基本信息
		ShoporderFormMap shoporderFormMap = new ShoporderFormMap();
		shoporderFormMap.put("shoporder_no", shoporderNo);
		shoporderFormMap.put("site_id", siteId);
		List<ShoporderFormMap> listShoporderFormMap = baseMapper.findByNames(shoporderFormMap);
		if (!ListUtils.isNotNull(listShoporderFormMap)) {
			String errMessage = "未检索到工单编号为：" + shoporderNo.toUpperCase() + "的信息";
			log.error(errMessage);
			model.addAttribute("res", findByRes());
			model.addAttribute("errorMessage", errMessage);
			return shoporderIssuingUrl;
		}
		shoporderFormMap = listShoporderFormMap.get(0);
		
		//2.查询物料信息和物料清单信息
		String itemId = shoporderFormMap.getStr("shoporder_item_id");
		queryItemAndItemBom(model,itemId);
		
		//3.查询工艺路线信息
		String processWorkflowId = shoporderFormMap.getStr("process_workflow_id");
		queryProcessWorkflow(model,processWorkflowId);
		
		//4.查询工单下达数量和完成数量
		queryShoporderProductionNumber(shoporderFormMap);	
		
		//5.计算可下达数量
		int shoporderNumber = shoporderFormMap.getInt("shoporder_number");
		int shoporderIssuedNumber = shoporderFormMap.getInt("shoporder_issued_number");
		int canIssuingNumber = shoporderNumber - shoporderIssuedNumber;
		shoporderFormMap.put("can_issuing_number", canIssuingNumber);
	    
	    model.addAttribute("shoporderFormMap", shoporderFormMap);
		model.addAttribute("successMessage", "检索成功");
		setShoporderStatusList(model);
		return shoporderIssuingUrl;
	}
}